package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
	"path"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type MyFomatter struct {
	// 日志前缀
	Prefix string
	// 格式化时间
	Fomatter string
	// 是否需要行号
	NeedLine bool
	// 是否需要文件路径
	NeedPath bool
	// 是否需要文件名
	NeedFileName bool
	// 是否需要函数名
	NeedFuncName bool
}

// 日志颜色
const (
	green   = "\033[97;32m"
	white   = "\033[90;37m"
	yellow  = "\033[90;33m"
	red     = "\033[97;31m"
	blue    = "\033[97;34m"
	magenta = "\033[97;35m"
	cyan    = "\033[97;36m"
	reset   = "\033[0m"
)

func (m MyFomatter) Format(entry *logrus.Entry) ([]byte, error) {
	// 生成颜色
	var color string
	switch entry.Level {
	case logrus.ErrorLevel:
		color = red
	case logrus.WarnLevel:
		color = yellow
	case logrus.InfoLevel:
		color = blue
	case logrus.DebugLevel:
		color = magenta
	default:
		color = white
	}
	// 设置buffer
	var buffer *bytes.Buffer
	if entry.Buffer == nil {
		buffer = &bytes.Buffer{}
	} else {
		buffer = entry.Buffer
	}
	// 设置请求时间格式化
	time := entry.Time.Format("2006/01/02 15:04:05")
	var fileVal string
	if entry.HasCaller() {
		// 设置日志发生的文件、函数名、行号
		fileVal = fmt.Sprintf("%s %s %d", path.Base(entry.Caller.File), entry.Caller.Func.Name(), entry.Caller.Line)
	}
	fmt.Fprintf(buffer, "[%s] %s[%s]%s [%s] %s %s\n", m.Prefix, color, entry.Level, reset, time, fileVal, entry.Message)
	return buffer.Bytes(), nil
}

func main3() {
	router := gin.New()
	gin.SetMode(gin.ReleaseMode)
	logrus.SetLevel(logrus.DebugLevel)
	logrus.SetFormatter(&MyFomatter{Prefix: "GinApp"})
	logrus.SetReportCaller(true)

	file, _ := os.OpenFile("./logs/info.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
	outLine := []io.Writer{
		file,
		os.Stdout,
	}
	logrus.SetOutput(io.MultiWriter(outLine...))
	logrus.Warn("ok，来了")
	logrus.Error("ok，来了")
	logrus.Info("ok，来了")
	logrus.Debugf("ok，来了")
	router.SetTrustedProxies([]string{"127.0.0.1"})
	router.GET("/r2", func(ctx *gin.Context) {
		ctx.String(http.StatusOK, "你好啊")
	})
	router.GET("/r1", func(ctx *gin.Context) {
		ctx.String(http.StatusOK, "你好啊")
	})
	router.Run("127.0.0.1:8003")
}
